package com.example.weatherforecast;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.weatherforecast.citypagetool.RecentWeatherAdapter;
import com.example.weatherforecast.weatherdatatool.RecentWeatherInfo;
import com.example.weatherforecast.weatherdatatool.WeatherApi;
import com.example.weatherforecast.weatherdatatool.CurrentWeatherInfo;
import com.hxc.basemodule.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author：coderChen
 * @Project：WeatherForecast
 * Explain:主页面，显示城市天气以及最近10天天气
 */

public class MainActivity extends BaseActivity  {
    private RecyclerView recyclerView;
    private RecentWeatherAdapter adapter;
    private String cityCode = "101010100"; // 默认城市编码为北京

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.indexTitle);
        //将溢出的图标设置为白色
        toolbar.getOverflowIcon().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
        setSupportActionBar(toolbar);
        // 隐藏Toolbar的标题
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        // 设置沉浸式窗口
        setImmersiveWindows();

//        --------------------------------------
        // 获取ManageActivity传递的城市编号
//        Intent intent = getIntent();
//        String cityCode = "101010100"; // 默认城市编号为北京
//        if (intent.hasExtra("cityCode")) {
//            cityCode = intent.getStringExtra("cityCode");
//            Log.d("CityCode", "城市编号：" + cityCode);
//        }

//        Intent intent = getIntent();
//        String cityCode = "101010100"; // 默认城市编码为北京
//        if (intent != null && intent.hasExtra("cityIndex")) {
//            int cityIndex = intent.getIntExtra("cityIndex", -1);
//
//            // 从 SharedPreferences 中检索城市代码
//            SharedPreferences sharedPreferences = getSharedPreferences("CityData", Context.MODE_PRIVATE);
//            Set<String> citySet = sharedPreferences.getStringSet("cities", new HashSet<>());
//            List<String> cityList = new ArrayList<>(citySet);
//            if (cityIndex >= 0 && cityIndex < cityList.size()) {
//                cityCode = getCityCodeFromIndex(cityList.get(cityIndex)); // 从 cityList 中获取城市代码的方法
//                if (TextUtils.isEmpty(cityCode)) {
//                    cityCode = "101010100"; // 默认城市编码为北京
//                }
//            }
//        }
        // 从 SharedPreferences 中获取或设置城市编码
        SharedPreferences newSharedPreferences = getSharedPreferences("NewCityData", Context.MODE_PRIVATE);
         cityCode = newSharedPreferences.getString("cityCode", "101010100"); // 默认城市编码为北京

        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("cityIndex")) {
            int cityIndex = intent.getIntExtra("cityIndex", -1);

            // 从 SharedPreferences 中检索城市代码
            SharedPreferences sharedPreferences = getSharedPreferences("CityData", Context.MODE_PRIVATE);
            Set<String> citySet = sharedPreferences.getStringSet("cities", new HashSet<>());
            List<String> cityList = new ArrayList<>(citySet);
            if (cityIndex >= 0 && cityIndex < cityList.size()) {
                String selectedCityCode = getCityCodeFromIndex(cityList.get(cityIndex)); // 从 cityList 中获取城市代码的方法
                if (!TextUtils.isEmpty(selectedCityCode)) {
                    // 将选定的城市编码存储到新的 SharedPreferences 中
                    SharedPreferences.Editor editor = newSharedPreferences.edit();
                    editor.putString("cityCode", selectedCityCode);
                    editor.apply();
                    cityCode = selectedCityCode;
                }
            }
        }


        // 拼接 URL
        String url = "http://t.weather.sojson.com/api/weather/city/" + cityCode;

        // 在线程中发起网络请求并更新页面
        new Thread(new Runnable() {
            @Override
            public void run() {
                CurrentWeatherInfo currentWeatherInfo = WeatherApi.getWeatherData(url);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (currentWeatherInfo != null) {
                            // 显示解析到的城市天气数据
                            TextView cityNameTextView = findViewById(R.id.tvCityName1);
                            cityNameTextView.setText(currentWeatherInfo.getCityName());

                            TextView temperatureTextView = findViewById(R.id.tvTemperature);
                            temperatureTextView.setText(currentWeatherInfo.getTemperature() + "℃");

                            TextView lowestTemperatureTextView = findViewById(R.id.tvLowest);
                            lowestTemperatureTextView.setText(currentWeatherInfo.getLowestTemperature()+" / ");

                            TextView highestTemperatureTextView = findViewById(R.id.tvHighest);
                            highestTemperatureTextView.setText("" + currentWeatherInfo.getHighestTemperature());

                            TextView weatherTypeTextView = findViewById(R.id.tvType);
                            weatherTypeTextView.setText(currentWeatherInfo.getWeatherType()+" ");

                            TextView airQualityTextView = findViewById(R.id.tvQuality);
                            airQualityTextView.setText("空气"+ currentWeatherInfo.getAirQuality());

                            TextView updateTimeTextView = findViewById(R.id.tvUpdateTime);
                            updateTimeTextView.setText("上次更新时间："+ currentWeatherInfo.getUpdateTime());

                            TextView noticeTextView = findViewById(R.id.tvNotice);
                            noticeTextView.setText(currentWeatherInfo.getNotice());

                            List<RecentWeatherInfo> forecasts = currentWeatherInfo.getForecasts();
                            adapter = new RecentWeatherAdapter(forecasts);
                            recyclerView = findViewById(R.id.rvRecent);
                            recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                            recyclerView.setAdapter(adapter);
                            displayWeatherBackground(currentWeatherInfo);

                        } else {
                            // 处理获取天气数据失败的情况
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setMessage("获取数据失败，建议更换网络后重试！！！")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            // User clicked OK button
                                        }
                                    });
                            AlertDialog dialog = builder.create();
                            dialog.show();
                        }
                    }
                });
            }
        }).start();
    }
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK ) {
            //do something.
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    //创建主页选项式菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    //菜单点击事件处理
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.managecity) {
            // 处理“管理城市”菜单项的点击事件
            startActivity(new Intent(MainActivity.this, ManageActivity.class));
            return true;
        } else if (id == R.id.about) {
            // 处理“About”菜单项的点击事件
            AppInfoDialog.showAppInfoDialog(MainActivity.this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    //根据序号获取城市编码
    private String getCityCodeFromIndex(String cityData) {
        try {
            JSONObject cityObject = new JSONObject(cityData);
            return cityObject.getString("cityCode");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据天气类型加载不同的天气图片
    private void displayWeatherBackground(CurrentWeatherInfo weatherInfo) {
        // 从 CurrentWeatherInfo 对象中获取天气类型对应的背景图片资源
        int backgroundResource = weatherInfo.getWeatherTypeBackground();

        // 设置 ConstraintLayout 的背景为获取到的图片资源
        ConstraintLayout constraintLayout = findViewById(R.id.index);
        constraintLayout.setBackgroundResource(backgroundResource);
    }


}